// 通用调查问卷系统 - 服务器端
// 支持多调查并存、配置化问卷、数据持久化

const http = require('http');
const fs = require('fs');
const path = require('path');
const os = require('os');
const url = require('url');

const PORT = 3000;

// 工具函数: 获取本机IP地址
function getLocalIP() {
    const interfaces = os.networkInterfaces();
    for (let name of Object.keys(interfaces)) {
        for (let iface of interfaces[name]) {
            if (iface.family === 'IPv4' && !iface.internal) {
                return iface.address;
            }
        }
    }
    return 'localhost';
}

// 工具函数: 生成唯一ID
function generateSurveyId() {
    const date = new Date();
    const timestamp = date.getFullYear().toString() +
                     (date.getMonth() + 1).toString().padStart(2, '0') +
                     date.getDate().toString().padStart(2, '0') + '_' +
                     date.getHours().toString().padStart(2, '0') +
                     date.getMinutes().toString().padStart(2, '0') +
                     date.getSeconds().toString().padStart(2, '0');
    return `survey_${timestamp}`;
}

// 工具函数: 读取JSON文件
function readJSON(filePath) {
    try {
        if (!fs.existsSync(filePath)) {
            return null;
        }
        const content = fs.readFileSync(filePath, 'utf8');
        return JSON.parse(content);
    } catch (error) {
        console.error(`读取JSON失败: ${filePath}`, error.message);
        return null;
    }
}

// 工具函数: 写入JSON文件
function writeJSON(filePath, data) {
    try {
        const dir = path.dirname(filePath);
        if (!fs.existsSync(dir)) {
            fs.mkdirSync(dir, { recursive: true });
        }
        fs.writeFileSync(filePath, JSON.stringify(data, null, 2), 'utf8');
        return true;
    } catch (error) {
        console.error(`写入JSON失败: ${filePath}`, error.message);
        return false;
    }
}

// 工具函数: 获取所有调查列表
function getAllSurveys() {
    const surveysDir = path.join(__dirname, 'surveys');
    if (!fs.existsSync(surveysDir)) {
        fs.mkdirSync(surveysDir, { recursive: true });
        return [];
    }

    const files = fs.readdirSync(surveysDir);
    const surveys = [];

    files.forEach(file => {
        if (file.endsWith('.json')) {
            const surveyConfig = readJSON(path.join(surveysDir, file));
            if (surveyConfig) {
                // 读取对应的数据文件获取提交数量
                const dataPath = path.join(__dirname, 'data', file);
                const surveyData = readJSON(dataPath) || [];

                surveys.push({
                    surveyId: surveyConfig.surveyId,
                    title: surveyConfig.title,
                    createdAt: surveyConfig.createdAt,
                    status: surveyConfig.status || 'active',
                    submissionCount: surveyData.length
                });
            }
        }
    });

    return surveys.sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt));
}

// 工具函数: 获取调查配置
function getSurveyConfig(surveyId) {
    const configPath = path.join(__dirname, 'surveys', `${surveyId}.json`);
    return readJSON(configPath);
}

// 工具函数: 获取调查数据
function getSurveyData(surveyId) {
    const dataPath = path.join(__dirname, 'data', `${surveyId}.json`);
    return readJSON(dataPath) || [];
}

// 工具函数: 保存调查数据
function saveSurveyData(surveyId, data) {
    const dataPath = path.join(__dirname, 'data', `${surveyId}.json`);
    return writeJSON(dataPath, data);
}

// 工具函数: 读取HTML模板
function readHTMLTemplate(filename) {
    const filePath = path.join(__dirname, filename);
    try {
        return fs.readFileSync(filePath, 'utf8');
    } catch (error) {
        console.error(`读取HTML失败: ${filename}`, error.message);
        return null;
    }
}

// 创建HTTP服务器
const server = http.createServer((req, res) => {
    // 设置CORS
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
    res.setHeader('Access-Control-Allow-Headers', 'Content-Type');

    if (req.method === 'OPTIONS') {
        res.writeHead(200);
        res.end();
        return;
    }

    const parsedUrl = url.parse(req.url, true);
    const pathname = parsedUrl.pathname;

    // ========== 管理后台路由 ==========

    if (pathname === '/' || pathname === '/admin') {
        // 管理后台首页
        const html = readHTMLTemplate('admin.html');
        if (html) {
            res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
            res.end(html);
        } else {
            res.writeHead(500);
            res.end('管理后台页面加载失败');
        }
    }
    else if (pathname === '/api/templates') {
        // 获取所有模板列表
        const templatesDir = path.join(__dirname, 'templates');
        const templates = [];

        if (fs.existsSync(templatesDir)) {
            const files = fs.readdirSync(templatesDir);
            files.forEach(file => {
                if (file.endsWith('.json')) {
                    const template = readJSON(path.join(templatesDir, file));
                    if (template) {
                        templates.push({
                            templateId: template.templateId,
                            templateName: template.templateName,
                            description: template.description
                        });
                    }
                }
            });
        }

        res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
        res.end(JSON.stringify(templates));
    }
    else if (pathname === '/api/surveys') {
        // 获取所有调查列表
        const surveys = getAllSurveys();
        res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
        res.end(JSON.stringify(surveys));
    }
    else if (pathname === '/api/survey/create' && req.method === 'POST') {
        // 创建新调查
        let body = '';
        req.on('data', chunk => { body += chunk.toString(); });
        req.on('end', () => {
            try {
                const { templateId, title } = JSON.parse(body);

                // 读取模板
                const templatePath = path.join(__dirname, 'templates', `${templateId}.json`);
                const template = readJSON(templatePath);

                if (!template) {
                    res.writeHead(404, { 'Content-Type': 'application/json; charset=utf-8' });
                    res.end(JSON.stringify({ success: false, message: '模板不存在' }));
                    return;
                }

                // 生成新调查ID
                const surveyId = generateSurveyId();

                // 创建调查配置
                const surveyConfig = {
                    ...template,
                    surveyId: surveyId,
                    title: title || template.title,
                    createdAt: new Date().toISOString(),
                    status: 'active'
                };

                // 保存配置
                const configPath = path.join(__dirname, 'surveys', `${surveyId}.json`);
                if (writeJSON(configPath, surveyConfig)) {
                    console.log(`✅ 创建调查成功: ${surveyId} - ${title}`);
                    res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
                    res.end(JSON.stringify({
                        success: true,
                        surveyId: surveyId,
                        message: '调查创建成功'
                    }));
                } else {
                    res.writeHead(500, { 'Content-Type': 'application/json; charset=utf-8' });
                    res.end(JSON.stringify({ success: false, message: '保存配置失败' }));
                }
            } catch (error) {
                console.error('创建调查失败:', error.message);
                res.writeHead(400, { 'Content-Type': 'application/json; charset=utf-8' });
                res.end(JSON.stringify({ success: false, message: '请求格式错误' }));
            }
        });
    }
    else if (pathname.startsWith('/api/survey/') && pathname.endsWith('/config')) {
        // 获取或更新调查配置
        const surveyId = pathname.split('/')[3];

        if (req.method === 'GET') {
            const config = getSurveyConfig(surveyId);
            if (config) {
                res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
                res.end(JSON.stringify(config));
            } else {
                res.writeHead(404, { 'Content-Type': 'application/json; charset=utf-8' });
                res.end(JSON.stringify({ success: false, message: '调查不存在' }));
            }
        }
        else if (req.method === 'POST') {
            let body = '';
            req.on('data', chunk => { body += chunk.toString(); });
            req.on('end', () => {
                try {
                    const updatedConfig = JSON.parse(body);
                    const configPath = path.join(__dirname, 'surveys', `${surveyId}.json`);

                    if (writeJSON(configPath, updatedConfig)) {
                        console.log(`✅ 更新调查配置: ${surveyId}`);
                        res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
                        res.end(JSON.stringify({ success: true, message: '配置更新成功' }));
                    } else {
                        res.writeHead(500, { 'Content-Type': 'application/json; charset=utf-8' });
                        res.end(JSON.stringify({ success: false, message: '保存失败' }));
                    }
                } catch (error) {
                    console.error('更新配置失败:', error.message);
                    res.writeHead(400, { 'Content-Type': 'application/json; charset=utf-8' });
                    res.end(JSON.stringify({ success: false, message: '请求格式错误' }));
                }
            });
        }
    }
    else if (pathname.startsWith('/api/survey/') && pathname.endsWith('/delete') && req.method === 'POST') {
        // 删除调查
        const surveyId = pathname.split('/')[3];

        try {
            const configPath = path.join(__dirname, 'surveys', `${surveyId}.json`);
            const dataPath = path.join(__dirname, 'data', `${surveyId}.json`);

            if (fs.existsSync(configPath)) {
                fs.unlinkSync(configPath);
            }
            if (fs.existsSync(dataPath)) {
                fs.unlinkSync(dataPath);
            }

            console.log(`🗑️  删除调查: ${surveyId}`);
            res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
            res.end(JSON.stringify({ success: true, message: '调查已删除' }));
        } catch (error) {
            console.error('删除调查失败:', error.message);
            res.writeHead(500, { 'Content-Type': 'application/json; charset=utf-8' });
            res.end(JSON.stringify({ success: false, message: '删除失败' }));
        }
    }

    // ========== 学生端路由 ==========

    else if (pathname.startsWith('/student/')) {
        const surveyId = pathname.split('/')[2];
        const config = getSurveyConfig(surveyId);

        if (!config) {
            res.writeHead(404);
            res.end('调查不存在');
            return;
        }

        const html = readHTMLTemplate('student.html');
        if (html) {
            res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
            res.end(html);
        } else {
            res.writeHead(500);
            res.end('学生页面加载失败');
        }
    }
    else if (pathname.startsWith('/api/submit/') && req.method === 'POST') {
        // 提交调查数据
        const surveyId = pathname.split('/')[3];

        let body = '';
        req.on('data', chunk => { body += chunk.toString(); });
        req.on('end', () => {
            try {
                const submissionData = JSON.parse(body);
                submissionData.timestamp = new Date().toISOString();
                submissionData.surveyId = surveyId;

                // 读取现有数据
                const allData = getSurveyData(surveyId);
                allData.push(submissionData);

                // 保存数据
                if (saveSurveyData(surveyId, allData)) {
                    console.log(`✅ 收到提交: ${submissionData.name || '匿名'} (${surveyId}, 当前共${allData.length}份)`);
                    res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
                    res.end(JSON.stringify({ success: true, message: '提交成功' }));
                } else {
                    res.writeHead(500, { 'Content-Type': 'application/json; charset=utf-8' });
                    res.end(JSON.stringify({ success: false, message: '保存失败' }));
                }
            } catch (error) {
                console.error('提交数据失败:', error.message);
                res.writeHead(400, { 'Content-Type': 'application/json; charset=utf-8' });
                res.end(JSON.stringify({ success: false, message: '数据格式错误' }));
            }
        });
    }

    // ========== 教师端路由 ==========

    else if (pathname.startsWith('/teacher/')) {
        const surveyId = pathname.split('/')[2];
        const config = getSurveyConfig(surveyId);

        if (!config) {
            res.writeHead(404);
            res.end('调查不存在');
            return;
        }

        const html = readHTMLTemplate('teacher.html');
        if (html) {
            res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
            res.end(html);
        } else {
            res.writeHead(500);
            res.end('教师页面加载失败');
        }
    }
    else if (pathname.startsWith('/api/data/') && req.method === 'GET') {
        // 获取调查数据
        const surveyId = pathname.split('/')[3];
        const data = getSurveyData(surveyId);

        res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
        res.end(JSON.stringify(data));
    }
    else if (pathname.startsWith('/api/clear/') && req.method === 'POST') {
        // 清空调查数据
        const surveyId = pathname.split('/')[3];

        if (saveSurveyData(surveyId, [])) {
            console.log(`🗑️  清空数据: ${surveyId}`);
            res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
            res.end(JSON.stringify({ success: true, message: '数据已清空' }));
        } else {
            res.writeHead(500, { 'Content-Type': 'application/json; charset=utf-8' });
            res.end(JSON.stringify({ success: false, message: '清空失败' }));
        }
    }

    // ========== 404 ==========
    else {
        res.writeHead(404);
        res.end('404 Not Found');
    }
});

// 启动服务器
server.listen(PORT, '0.0.0.0', () => {
    const localIP = getLocalIP();
    console.log('\n========================================');
    console.log('📊 通用调查问卷系统已启动！');
    console.log('========================================\n');
    console.log('👨‍🏫 管理后台地址:');
    console.log(`   http://${localIP}:${PORT}/admin`);
    console.log(`   或 http://localhost:${PORT}/admin\n`);
    console.log('💡 在管理后台可以:');
    console.log('   - 创建新调查(选择模板)');
    console.log('   - 编辑调查配置');
    console.log('   - 查看学生提交数据');
    console.log('   - 导出数据报表\n');
    console.log('🛑 按 Ctrl+C 停止服务器');
    console.log('========================================\n');
});
